package com.zyh.dom4j.demo2;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;

/**
 * @Author zyh
 * @Date 2024/8/13 11:38
 * @Description
 */

public class Dom4jDemo2 {
    public static void main(String[] args) throws IOException {
        //创建一个document对象
        Document document = DocumentHelper.createDocument();
        //添加根节点元素
        Element games = document.addElement("games");
        //通过根节点元素添加子节点元素
        Element game1 = games.addElement("game");
        //添加子节点元素的属性
        game1.addAttribute("id","1");
        //添加子节点的孙子节点元素
        Element name1 = game1.addElement("name");
        //为孙子节点元素添加内容
        name1.addText("完美国际");
        Element company1 = game1.addElement("company");
        company1.addText("完美世界");

        Element game2 = games.addElement("game");
        game2.addAttribute("id","2");
        Element name2 = game2.addElement("name");
        name2.addText("LOL");
        Element company2 = game2.addElement("company");
        company2.addText("Tencent");

        Element game3 = games.addElement("game");
        game3.addAttribute("id","3");
        Element name3 = game3.addElement("name");
        name3.addText("DOTA");
        Element company3 = game3.addElement("company");
        company3.addText("暴雪");

        //创建一个写的模板，使用OutputFormat调用打印方法
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");//设置文件编码
        //指定写到哪里
        XMLWriter xmlWriter = new XMLWriter(new FileWriter("D:\\Code\\IDEA\\idea_projects\\JavaSE-plus\\day15-code\\src\\com\\zyh\\dom4j\\demo2\\newGames.xml"),format);
        xmlWriter.write(document);
        xmlWriter.close();
    }
}
